﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IOA.MES.Business
{
    /// <summary>
    /// 电池参数管理
    /// </summary>
    public class CellParaMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 查询参数列表
        /// </summary>
        /// <param name="type">参数类型</param>
        /// <returns>参数列表</returns>
        public List<VCellPara> QueryParas(ParaType? type)
        {
            var entities = mesDb.CellParas.AsNoTracking().Where(_ => (!type.HasValue || _.ParaType == type.Value) && _.Valid).OrderBy(_ => _.ParaValue).ToList();
            return Mapper.Map<List<VCellPara>>(entities);
        }

        /// <summary>
        /// 查询参数列表
        /// </summary>
        /// <param name="type">参数类型</param>
        /// <param name="paras">参数列表</param>
        /// <param name="@operator">操作人</param>
        public void SaveParas(ParaType type, List<VCellPara> paras, int @operator)
        {
            var entities = mesDb.CellParas.AsNoTracking().Where(_ => _.ParaType == type && _.Valid).ToList();
            var newParas = paras.Where(para => !entities.Select(_ => _.ParaValue).Contains(para.ParaValue)).ToList();
            var removeParas = entities.Where(para => !paras.Select(_ => _.ParaValue).Contains(para.ParaValue)).ToList();
            newParas.ForEach(_ =>
            {
                _.CreateBy = @operator;
                _.ParaType = type;
                _.CreateTime = DateTime.Now;
            });
            mesDb.CellParas.AddRange(Mapper.Map<List<CellPara>>(newParas));
            removeParas.ForEach(_ =>
            {
                mesDb.CellParas.Attach(_);
                _.Valid = false;
                _.ModifyBy = @operator;
                _.CreateTime = DateTime.Now;
            });
            mesDb.SaveChanges();
        }
    }
}
